/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-violationInquiry
*
* @File name : JuHeViolationService.java
*
* @Author : Administrator
*
* @Date : 2017年12月12日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年12月12日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.violationInquiry.service;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dto.customerInfo.MemberDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.service.violationInquiry.constant.ViolationInquiryConstant;
import com.yonyou.gmmc.service.violationInquiry.dao.TmRegulationsMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TmViolationCityMapper;
import com.yonyou.gmmc.service.violationInquiry.dao.TtViolationMapper;
import com.yonyou.gmmc.service.violationInquiry.model.TmViolationCity;
import com.yonyou.gmmc.service.violationInquiry.model.TtViolation;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author Administrator
 * @date 2017年12月12日
 */
@Service
@Transactional
public class JuHeViolationService {

	private Logger logger = Logger.getLogger(JuHeViolationService.class);

	@Autowired
	private TmViolationCityMapper tmViolationCityMapper;

	@Autowired
	private TmRegulationsMapper tmRegulationsMapper;

	@Autowired
	private SaveThridService saveThridService;

	@Autowired
	private TtViolationMapper ttViolationMapper;

	@Value("${JH_KEY}")
	private String JH_KEY;
	@Value("${VIOLATIONTIME}")
	private Integer violationTime;

	/**
	 * 获取支持城市-聚合数据
	 * 
	 * @author Administrator
	 * @date 2017年12月12日
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String violationCity() {
		String param = "province=&dtype=json&key=" + JH_KEY;
		String returnJson = FrameHttpUtil.sendGet("http://v.juhe.cn/wz/citys?", param);
		JSONObject json = JSONObject.fromObject(returnJson);
		String error_code = json.getString("error_code");
		String reason = json.getString("reason");
		logger.info("接口返回码为：" + error_code + "-----返回信息为：" + reason);
		if (error_code.equals("0")) {
			logger.info("查询成功，拿到返回数据进行处理");
			if (!CheckUtil.NullOrEmpty(json.getString("result"))) {
				Map<String, Object> result = JSONObject.fromObject(json.getString("result"));
				for (Map.Entry<String, Object> m : result.entrySet()) {
					String province_code = m.getKey();
					JSONObject jsonProvince = JSONObject.fromObject(m.getValue());
					String province = jsonProvince.getString("province");
					if (!CheckUtil.NullOrEmpty(jsonProvince.getString("citys"))) {
						JSONArray citys = JSONArray.fromObject(jsonProvince.getString("citys"));
						for (Object c : citys) {
							JSONObject jsonCity = JSONObject.fromObject(c);
							TmViolationCity record = new TmViolationCity();
							record.setAbbr(jsonCity.getString("abbr"));
							record.setCityCode(jsonCity.getString("city_code"));
							record.setCityName(jsonCity.getString("city_name"));
							record.setClassa(Integer.valueOf(jsonCity.getString("classa")));
							record.setClassno(Integer.valueOf(jsonCity.getString("classno")));
							record.setCreateBy(ViolationInquiryConstant.OPT_USER);
							record.setCreateDate(new Date());
							record.setEngine(Integer.valueOf(jsonCity.getString("engine")));
							record.setEngineno(Integer.valueOf(jsonCity.getString("engineno")));
							record.setProvince(province);
							record.setProvinceCode(province_code);
							Example example = new Example(TmViolationCity.class);
							example.createCriteria().andCondition("CITY_NAME=", jsonCity.getString("city_name"));
							List<TmViolationCity> list = tmViolationCityMapper.selectByExample(example);
							if (list.size() == 0) {
								tmViolationCityMapper.insertSelective(record);
							} else {
								tmViolationCityMapper.updateByExampleSelective(record, example);
							}
						}
					} else {
						throw new ServiceBizException("支持违章查询暂不支持该城市");
					}
				}
			} else {
				throw new ServiceBizException("支持违章查询暂不支持该城市");
			}
		} else {
			throw new ServiceBizException(reason);
		}
		return error_code;
	}

	/**
	 * 前端获取城市列表
	 * 
	 * @author Administrator
	 * @date 2017年12月12日
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> checkCitys() {
		List<Map<String, Object>> resultList = new ArrayList<>();
		List<TmViolationCity> provinceList = tmViolationCityMapper.selectProList();
		if (provinceList.size() > 0) {
			for (TmViolationCity dto : provinceList) {
				Map<String, Object> firstMap = new HashMap<>();
				List<Map<String, Object>> deList = new ArrayList<>();
				TmViolationCity vCity = new TmViolationCity();
				vCity.setProvinceCode(dto.getProvinceCode());
				List<TmViolationCity> cityList = tmViolationCityMapper.select(vCity);
				if (cityList.size() > 0) {
					for (TmViolationCity child : cityList) {
						Map<String, Object> deMap = new HashMap<>();
						deMap.put("name", child.getCityName());
						deMap.put("id", child.getCityCode());
						deList.add(deMap);
					}
				}
				firstMap.put("shortName", dto.getAbbr());
				firstMap.put("name", dto.getProvince());
				firstMap.put("id", dto.getProvinceCode());
				firstMap.put("child", deList);
				resultList.add(firstMap);
			}
		} else {
			throw new ServiceBizException("违章查询支持城市列表为空");
		}
		return resultList;
	}

	/**
	 * 根据城市获取发动机和车架号
	 * 
	 * @author Administrator
	 * @date 2017年12月12日
	 * @param cityCode
	 * @return
	 */
	public List<TmViolationCity> checkEngineAndVin(String cityCode) {
		List<TmViolationCity> result = new ArrayList<>();
		Example example = new Example(TmViolationCity.class);
		example.createCriteria().andCondition("CITY_CODE=", cityCode);
		result = tmViolationCityMapper.selectByExample(example);
		if (CheckUtil.NullOrEmpty(result)) {
			throw new ServiceBizException("该地区暂不支持违章查询!");
		}
		return result;
	}

	public Map<String, Object> violation(Map<String, String> map) throws Exception {
		Map<String, Object> result = new HashMap<>();
		// 扣分总数
		Integer sumNum = 0;
		// 罚款总数
		Integer sumMoney = 0;
		// 保存查询历史
		saveThridService.saveThrid(map);
		Example example = new Example(TtViolation.class);
		example.createCriteria().andCondition("HPHM=", map.get("registNo"));
		example.setOrderByClause("ACT_DATE DESC");
		List<TtViolation> list = new ArrayList<>();
		list = ttViolationMapper.selectByExample(example);
		if (list.size() == 0) {
			logger.info("该车牌并未有过查询记录");
			list = selectViolationByJuHe(map);
		} else {
			logger.info("查询该车牌违章查询时间与本次相差多久");
			Date createDate = list.get(0).getCreateDate();
			long b = new Date().getTime() - createDate.getTime();
			if (b > violationTime) {
				logger.info("距离上次查询间隔超过指定时间，重新调用违章查询接口");
				list = selectViolationByJuHe(map);
			}else{
				logger.info("距离上次查询间隔未超过指定时间，查询本地数据。。。");
				TtViolation vio = new TtViolation();
				vio.setHphm(map.get("registNo"));
				vio.setHandled("0");
				list = ttViolationMapper.select(vio);
			}
		}
		Map<String, Object> carMap = tmRegulationsMapper.queryCar(map.get("registNo"));
		if (carMap != null && !carMap.isEmpty()) {
			result.put("seriesName", carMap.get("seriesName"));
			result.put("carName", carMap.get("carName"));
			result.put("picUrl", carMap.get("picUrl"));
		} else {
			result.put("seriesName", null);
			result.put("carName", null);
			result.put("picUrl", null);
		}
		if (!CheckUtil.NullOrEmpty(list)) {
			for (TtViolation dto : list) {
				sumNum = sumNum + Integer.valueOf(dto.getFen());
				sumMoney = sumMoney + Integer.valueOf(dto.getMoney());
			}
		}
		result.put("registNo", map.get("registNo"));
		result.put("sumNum", sumNum);
		result.put("sumMoney", sumMoney);
		// 违规总数
		result.put("illeagalNum", list.size());
		result.put("list", list);
		result.put(ResultMsgConstants.RESULT_FLAG, ResultMsgConstants.RESULT_FLAG_SUCCESS);
		result.put(ResultMsgConstants.RESULT_MESSAGE, "");
		return result;
	}

	/**
	 * 调用聚合数据接口查询车辆违章记录
	 * 
	 * @author Administrator
	 * @date 2017年12月13日
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public List<TtViolation> selectViolationByJuHe(Map<String, String> map) throws Exception {
		List<TtViolation> resultList = new ArrayList<TtViolation>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			String param = "dtype=json&city=" + map.get("city") + "&hphm="
					+ URLEncoder.encode(map.get("registNo"), "UTF-8") + "&hpzl=02&engineno=" + map.get("engine")
					+ "&classno=" + map.get("vin") + "&key=" + JH_KEY;
			String returnJson = FrameHttpUtil.sendGet("http://v.juhe.cn/wz/query?", param);
			JSONObject json = JSONObject.fromObject(returnJson);
			String error_code = json.getString("error_code");
			String reason = json.getString("reason");
			logger.info("接口返回码为：" + error_code + "-----返回信息为：" + reason);
			if (error_code.equals("0")) {
				logger.info("查询成功，拿到返回数据进行处理");
				if (!CheckUtil.NullOrEmpty(json.getString("result"))) {
					JSONObject result = JSONObject.fromObject(json.getString("result"));
					String province = result.getString("province");
					String city = result.getString("city");
					String hphm = result.getString("hphm");
					String hpzl = result.getString("hpzl");
					if (!CheckUtil.NullOrEmpty(result.getString("lists"))) {
						JSONArray lists = JSONArray.fromObject(result.getString("lists"));
						List<Date> daList = new ArrayList<>();
						for (Object l : lists) {
							JSONObject jsonLists = JSONObject.fromObject(l);
							TtViolation violation = new TtViolation();
							String date = jsonLists.getString("date");
							String area = jsonLists.getString("area");
							String act = jsonLists.getString("act");
							String code = jsonLists.getString("code");
							String fen = jsonLists.getString("fen");
							String money = jsonLists.getString("money");
							String handled = jsonLists.getString("handled");
							String wzcity = jsonLists.getString("wzcity");
							String archiveno = jsonLists.getString("archiveno");
							Date actDate = sdf.parse(date);
							daList.add(actDate);
							violation.setActDate(actDate);
							violation.setAct(act);
							violation.setArea(area);
							violation.setCity(city);
							violation.setCode(code);
							violation.setCreateBy(ViolationInquiryConstant.OPT_USER);
							violation.setCreateDate(new Date());
							violation.setFen(fen);
							violation.setHandled(handled);
							violation.setHphm(hphm);
							violation.setHpzl(hpzl);
							violation.setMoney(money);
							violation.setProvince(province);
							violation.setWzcity(wzcity);
							violation.setArchiveno(archiveno);
							// 把时间戳 转成 2017-04-02 星期二 20:07:00
							violation.setExcuteTime(date.substring(0, 11)
									+ DateUtil.getWeek(DateUtil.dateFormat(date, "yyyy-MM-dd HH:mm:ss")) + date.substring(10));

							Example ex = new Example(TtViolation.class);
							Criteria criteria = ex.createCriteria();
							criteria.andEqualTo("hphm", hphm);
							criteria.andEqualTo("actDate", actDate);
							List<TtViolation> list = ttViolationMapper.selectByExample(ex);
							if(CheckUtil.NullOrEmpty(list)){
								int a = ttViolationMapper.insertSelective(violation);
								logger.info("成功保存" + a + "条违章记录");
							}else{
								int a = ttViolationMapper.updateByExampleSelective(violation, ex);
								logger.info("成功更新" + a + "条违章记录");
							}
							resultList.add(violation);
							
							
						}
						Example ex1 = new Example(TtViolation.class);
						Criteria criteria1 = ex1.createCriteria();
						criteria1.andEqualTo("hphm", hphm);
						criteria1.andNotIn("actDate", daList);
						
						TtViolation vio= new TtViolation();
						vio.setHandled("1");
						vio.setUpdateBy(ViolationInquiryConstant.OPT_USER);
						vio.setUpdateDate(new Date());
						
						int a = ttViolationMapper.updateByExampleSelective(vio, ex1);
						logger.info("成功更新" + a + "条违章记录");
					}
				} else {
					throw new ServiceBizException("查询不到违章记录");
				}
			} else {
				throw new ServiceBizException(reason);
			}
			return resultList;
		} catch (Exception e) {
			logger.info("Exception:", e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public Map<String, Object> checkCar(Map<String, Object> map) {
		Map<String, Object> result = new HashMap<>();
		Integer userId = Integer.valueOf(map.get("userId").toString());
		logger.info("ViolationInquiryService.checkCar==>userId:" + map.get("userId"));
		MemberDto memberDto = tmRegulationsMapper.queryMember(userId);
		// 判断是否为会员
		if (memberDto == null) {
			logger.info(">>>>>粉丝不能使用！");
			result.put("typeCode", "0");
			result.put("typeName", "粉丝");
			return result;
		}
		// 判断是否为会员
		if (memberDto != null && memberDto.getVin() == null) {
			logger.info(">>>>>该用户为会员！");
			result.put("typeCode", "1");
			result.put("typeName", "会员");
			return result;
		}
		String carnumber = "";
		String vin = "";
		String engine = "";
		if (memberDto != null) {
			carnumber = memberDto.getLicenseNo();
			vin = memberDto.getVin();
			engine = memberDto.getEngine();
		}
		String licenseNo = carnumber.replaceAll(" ", "");
		result.put("typeCode", "2");
		result.put("typeName", "车主");
		result.put("vin", vin);
		result.put("licenseNo", licenseNo);
		result.put("engine", engine);

		return result;
	}
}
